package com.adcc.ags.cgw.service;

import com.adcc.ags.cgw.entity.msg.CGWMsg;
import com.adcc.ags.cgw.entity.msg.MsgType;
import com.adcc.ags.cgw.entity.user.User;
import com.adcc.ags.cgw.managed.proxy.MsgProxy;
import com.adcc.ags.cgw.managed.uplink.UplinkForward;
import com.adcc.ags.cgw.utils.Constant;
import com.adcc.utility.log.Log;
import com.adcc.utility.msg620.ACARS620Verification;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Map;

/**
 * 报文校验服务
 */
public class MsgVerificationServiceImpl extends MsgVerificationService {

    @Override
    protected boolean verify(String message) {

        // maxLength为0，则不进行长度校验
        if (UplinkForward.getInstance().getMaxLength() == 0) {
            return ACARS620Verification.verify(message);
        } else {
            return ACARS620Verification.verify(message, UplinkForward.getInstance().getMaxLength());
        }
    }

    @Override
    public void onReceive(Object message) {
        super.onReceive(message);

        try {
            if (message instanceof Map) {

                Map<String, Object> map = (HashMap<String, Object>) message;
                if (map.get(Constant.STRING_VERIFY_ACTOR_KEY1) != null && map.get(Constant.STRING_VERIFY_ACTOR_KEY2) != null) {

                    // 获取CGWMsg
                    CGWMsg cgwMsg = (CGWMsg) map.get(Constant.STRING_VERIFY_ACTOR_KEY1);

                    // 获取User
                    User user = (User) map.get(Constant.STRING_VERIFY_ACTOR_KEY2);

                    // 对上行报文进行校验，如果620校验失败丢弃错误报文
                    if (cgwMsg.getType() == MsgType.Uplink) {
                        byte[] buffer = cgwMsg.getContent().getContent();
                        if (!verify(new String(buffer, 0, buffer.length))) {
                            Log.error(MsgVerificationService.class.getName(), "verify message failed from user:" + user.getName() + "\r\n" + cgwMsg.getContent());

                            // 消息入库处理
                            saveMsg(cgwMsg, "F", Strings.nullToEmpty(""), Constant.STRING_ERROR_CODE_VERIFYFAILED);
                            return;
                        }
                    }
                    Map<String, Object> filterMap = Maps.newHashMapWithExpectedSize(2);
                    filterMap.put(Constant.STRING_FILTER_ACTOR_KEY1, cgwMsg);
                    filterMap.put(Constant.STRING_FILTER_ACTOR_KEY2, user);
                    MsgProxy.getInstance().getMsgFilterActor().tell(filterMap, this.getSelf());
                } else {
                    unhandled(message);
                }
            } else {
                unhandled(message);
            }
        } catch (Exception ex) {
            Log.error(MsgVerificationService.class.getName(), "onReceive() error", ex);
        }
    }
}
